<?php

namespace App\Http\Controllers\Payment;

use App\Models\RechargeRecord;
use App\Models\RechargeTemplets;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Payment\Client\Charge;
use Payment\Config;
use Illuminate\Support\Facades\Validator;
use Payment\Client\Notify;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Log;
use Illuminate\Support\Facades\Auth;
use DB;

date_default_timezone_set('Asia/Shanghai');

class AlipayController extends Controller
{
	
	
	/**
	 * 支付宝服务器异步通知
	 * 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
	 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
	 * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
	 * 4、验证app_id是否为该商户本身。
	 * 5、其它业务逻辑情况
	 * 
	 * @param $request
	 * @return mixed
	 */
	public function getNotifyurl(Request $request)
	{
		logger('收到异步通知');
		$alipay = Pay::alipay();
		
		try{
			$data = $alipay->verify($request->all());

			Log::debug('Alipay notify', $data->all());


            if ($data['trade_status'] != 'TRADE_SUCCESS') return false;

			$record = RechargeRecord::where('sn', $data['out_trade_no'])->first();
			$record_pay_amount = number_format($record->pay_amount, 2);
			if (!$record || $record_pay_amount != $data['total_amount'])
			    return false;

            $record->pay_sn = $data['trade_no'];
            $record->status = 'success';
            $record->save();

            User::where('id', $record->user_id)->increment('coin', $record->amount);
			
		} catch (Exception $e) {
			// $e->getMessage();
		}
		
		return $alipay->success();
	}
	
	public function getPay(Request $request)
	{
		$templet_id = $request->get('pid');
		$type = $request->get('type');
		
		$validator = Validator::make($request->all(), [
            'pid' => 'required|Numeric',
            'type' => ['required']
		]);
		
		if ($validator->fails()) {
			return response()->json($validator->messages(), 200);
		}
		$user_id = Auth::id();
		//检查改用户是否达到次数限制和金额限制
		
// 		$result = DB::table('recharge_records')->select(DB::raw('sum(amount) AS total_amount, count(id) AS total_count'))->where([['user_id','=',$user_id],['status','=','success']])->first();
// 		if ($result->total_amount || $result->total_amount)
// 		{
// 			return response()->json('次数受限', 200);
// 		}

		if ($type != 'cz')
            return response()->json(['status' => 'error', 'message' => 'Type Error!'], 200);


        //充值,得去查找对应的模板,再找到对应的套餐金额，$amount 套餐金额
        $recharge_templets = RechargeTemplets::find($templet_id);

        if (!$recharge_templets)
            return response('非法参数', 200);

        $amount = $recharge_templets->amount;
        $coin = $recharge_templets->coin;
        $body = $recharge_templets->name;//商品描述
        $subject = $recharge_templets->description ? $recharge_templets->description : $recharge_templets->name;//商品名称

		
		// 订单信息
		$orderNo = '2'. time() . rand(1000, 9999);//订单开头第一位为2，表示支付宝web 的订单

        //生成一条订单消息
        $save_data = [
            'sn' => $orderNo,//支付宝交易凭证号
            'pay_amount' => $amount,//支付金额
            'user_id' => Auth::id(),
            'templet_id' => $templet_id,
            'type' => 'user',
            'pay_way' => 'alipay-web',
            'pay_sn' => '',
            'amount' => intval($coin),
        ];
        $recharge_records = RechargeRecord::create($save_data);

		$order = [
            'out_trade_no' => $orderNo,
            'total_amount' => $amount,
            'subject' => $subject,
            'body' => $body,
            'passback_params' => $templet_id,
            'goods_type' => 0,
            'timeout_express' => '10m',
		];

		return Pay::alipay()->web($order);
	}
	
	/**
	 *  支付宝页面跳转同步通知,仅作为通知用户
	 */
	public function getReturnUrl(Request $request)
	{
		$data = $request->all();
		
		$alipay = Pay::alipay();
		$result = $alipay->verify($data);
		
		return view('home/payment_success');
	}
}
